package adminService

import (
	"fmt"
	adminDto "news_for_deepseek_interface/dto/admin"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
	"news_for_deepseek_interface/utils"
	"strconv"
	"time"
)

// 查找token
func FindToken(accessToken string) (adminTokenStruct adminModel.AdminTokenStruct, err error) {
	db := model.GetInstance().GetDB().Model(&adminModel.AdminTokenStruct{})
	if err = db.Where("access_token = ?", accessToken).First(&adminTokenStruct).Error; err != nil {
		err = fmt.Errorf("token不存在：%v", err)
		return
	}
	return
}

// 刷新token
func RefreshToken(params adminDto.RefreshTokenRequest) (response adminDto.RefreshTokenResponse, err error) {

	db := model.GetInstance().GetDB().Model(&adminModel.AdminTokenStruct{})

	var adminTokenStruct adminModel.AdminTokenStruct
	if err = db.Where("refresh_token = ?", params.RefreshToken).First(&adminTokenStruct).Error; err != nil {
		err = fmt.Errorf("token不存在：%v", err)
		return
	}

	accessToken, refreshToken, expires, err := UpdateAccessToken(adminTokenStruct.AdminId)
	if err != nil {
		err = fmt.Errorf("token刷新失败：%v", err)
		return
	}

	response = adminDto.RefreshTokenResponse{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
		Expires:      expires,
	}

	return
}

// 生成token
func CreateAccessToken(adminId int) (accessToken, refreshToken string, expires string, err error) {
	accessToken = utils.GenerateString(8) + strconv.Itoa(adminId) + utils.GenerateString(8)
	refreshToken = utils.GenerateString(8) + strconv.Itoa(adminId) + utils.GenerateString(8)
	expires = time.Now().Add(2 * time.Hour).Format("2006-01-02 15:04:05")

	model.GetInstance().GetDB().Table("admin_token").Create(map[string]interface{}{
		"admin_id":      adminId,
		"access_token":  accessToken,
		"refresh_token": refreshToken,
		"expires":       expires,
	})

	return
}

// 更新token
func UpdateAccessToken(adminId int) (accessToken, refreshToken string, expires string, err error) {
	accessToken = utils.GenerateString(8) + strconv.Itoa(adminId) + utils.GenerateString(8)
	refreshToken = utils.GenerateString(8) + strconv.Itoa(adminId) + utils.GenerateString(8)
	expires = time.Now().Add(2 * time.Hour).Format("2006-01-02 15:04:05")

	model.GetInstance().GetDB().Table("admin_token").Where("admin_id = ?", adminId).Updates(map[string]interface{}{
		"access_token":  accessToken,
		"refresh_token": refreshToken,
		"expires":       expires,
	})

	return
}
